<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar title="搜索结果" left-arrow @click-left="$router.back()" fixed />

    <!-- 上拉加载 -->
    <van-list
    v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
  :immediate-check="false" >
    <!-- 循环渲染的item组件 -->
     <art-item v-for="item in searchList" :key="item.art_id.toString()" :article='item' :closeable='false'></art-item>
     </van-list>
  </div>
</template>

<script>
import ArtItem from '@/components/AriItem/ArtItem.vue'
import { getSearchResultAPI } from '@/API/searchAPI.js'
export default {
  components: { ArtItem },
  props: ['kw'], // 获取动态参数
  name: 'SearchResult',
  data () {
    return {
      page: 1, // 页码
      searchList: [], // 返还的数据
      loading: false,
      finished: false,
      prekw: '' // 上次的搜索关键字
    }
  },
  methods: {
    // 获取搜索结果
    async  initSearchList () {
      const { data: res } = await getSearchResultAPI(this.kw, this.page)
      // console.log(res)
      if (res.message === 'OK') {
        console.log(this.searchList)
        this.searchList = [...this.searchList, ...res.data.results]// 拼接数据
        console.log(this.searchList)
        this.loading = false // 重置为flase
        // 判断数据总数
        if (res.data.results.length === 0) {
          this.finished = true
        }
        // 页码加1,为下一次请求数据做准备
        this.page += 1
      }
    },
    onLoad () { // 上拉加载更多
      this.initSearchList()
    }

  },
  created () {
    // 调用获取搜索结果
    this.initSearchList()
  },
  activated () {
    console.log('我是activated')
    if (this.prekw !== '' && this.prekw !== this.kw) { // 如果上次的关键字!==这次输入的关键字
      // 清空数据
      this.page = 1
      this.searchList = []
      this.loading = false
      this.finished = false
      // 重新发送请求
      this.initSearchList()
    }
  },
  deactivated () { // 在组件已经被缓存,并且再次进入时触发
    console.log('我是deactivated')
    this.prekw = this.kw // 把上次输入的关键字赋值给prekw
  }

}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
